package com.lottery.ruok.lottrey.activity;

import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.android.lib.dialog.NetWaitDialog;
import com.applozic.mobicomkit.ApplozicClient;
import com.applozic.mobicomkit.database.MobiComDatabaseHelper;
import com.google.gson.Gson;
import com.lottery.ruok.lottrey.BuildConfig;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.chat.RongCloudChatActivityHelper;
import com.lottery.ruok.lottrey.common.Common;
import com.lottery.ruok.lottrey.eventbusObject.LogOut;
import com.lottery.ruok.lottrey.eventbusObject.UpdateApk;
import com.lottery.ruok.lottrey.retrofitModule.RetrofitBase;
import com.lottery.ruok.lottrey.retrofitModule.RxHelper;
import com.lottery.ruok.lottrey.retrofitModule.RxSubscribe;
import com.lottery.ruok.lottrey.retrofitModule.request.GetProfileRequest;
import com.lottery.ruok.lottrey.retrofitModule.request.GroupPacketRequest;
import com.lottery.ruok.lottrey.retrofitModule.response.GetProfileResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.GroupPacketResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.UpdatePreResponse;
import com.lottery.ruok.lottrey.retrofitModule.response.UpdateResponse;
import com.lottery.ruok.lottrey.userInfo.UserInfo;
import com.lottery.ruok.lottrey.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Completable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Action;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import umeng.UpdateDialog;
import umeng.Version;
import utils.Utils;

/**
 * Created by ASUS on 2017/7/25.
 */

public class BaseActivity extends AppCompatActivity {
    protected CompositeDisposable disposables;
    //    protected Tracker mTracker;
    private Disposable getProfileAction;
    private int getProfileActionTime;


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (disposables != null) {
            if (disposables.size() > 0) {
                disposables.dispose();
            }
        }

        if (getProfileAction != null) {
            getProfileAction.dispose();
        }
    }

//    public void sendAnalyticMsg(String msg){
//        mTracker.send(new HitBuilders.EventBuilder()
//                .setCategory(Common.LOTTERY_ANDROID_ACTION)
//                .setAction(msg)
//                .build());
//    }

    protected void gotoChatRoom(String lotteryCode) {
        /*if (UserInfo.getRoomId() != 0) {
            Intent intent = new Intent(BaseActivity.this, ConversationActivity.class);
            intent.putExtra(ConversationUIService.GROUP_ID, UserInfo.getRoomId());
            startActivity(intent);
        } else {
            Utils.showToast("您暂时没有加入聊天房间");
        }*/
        if (lotteryCode == null) {
            lotteryCode = "bjpk10";
        }
        if (StringUtils.isNotEmpty(UserInfo.getRoomId())) {
            RongCloudChatActivityHelper.startChatRoomChat(this, UserInfo.getRoomId(), true, lotteryCode, UserInfo.getRoomName());
        } else {
            Toast.makeText(this, "聊天室不存在，请稍后再试", Toast.LENGTH_SHORT).show();
        }
    }

    protected void getRedPacketNum(final ImageView ball_view) {
        if (!UserInfo.getToken().equals("") && StringUtils.isNotEmpty(UserInfo.getRoomId())) {
            RetrofitBase.getRetrofit().create(GroupPacketRequest.class).getResult(UserInfo.getRoomId())
                    .compose(RxHelper.<GroupPacketResponse>handleResult())
                    .subscribe(new RxSubscribe<GroupPacketResponse>(BaseActivity.this) {
                        @Override
                        protected void _onNext(final GroupPacketResponse getProfileResponse) {
                            if (getProfileResponse != null) {
                                if (getProfileResponse.getCount() > 0) {
                                    ball_view.setImageResource(R.mipmap.red_packet);
                                }
                            }
                        }

                        @Override
                        public void onError(Throwable e) {//do nothing
                        }

                        @Override
                        protected boolean showDialog() {
                            return false;
                        }
                    });
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        getProfileActionTime = 0;

//        MyApplication application = (MyApplication) getApplication();
//        mTracker = application.getDefaultTracker();

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        getWindow().setBackgroundDrawable(null);

        disposables = new CompositeDisposable();

        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }

//        getWindow().getDecorView().setOnTouchListener(new View.OnTouchListener() {
//            @Override
//            public boolean onTouch(View view, MotionEvent motionEvent) {
//                removeSoftKeyboard(view);
//                return false;
//            }
//        });
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        try {
            if (ev.getAction() == MotionEvent.ACTION_DOWN) {
                View v = getCurrentFocus();
                if (isShouldHideKeyboard(v, ev)) {
                    hideKeyboard(v.getWindowToken());
                }
            }
            return super.dispatchTouchEvent(ev);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据EditText所在坐标和用户点击的坐标相对比，
     * 来判断是否隐藏键盘，因为当用户点击EditText时则不能隐藏
     */
    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] l = {0, 0};
            v.getLocationInWindow(l);
            int left = l[0],
                    top = l[1],
                    bottom = top + v.getHeight(),
                    right = left + v.getWidth();
            return !(event.getX() > left) || !(event.getX() < right)
                    || !(event.getY() > top) || !(event.getY() < bottom);
        }
        // 如果焦点不是EditText则忽略，这个发生在视图刚绘制完，第一个焦点不在EditText上，和用户用轨迹球选择其他的焦点
        return false;
    }

    /**
     * 获取InputMethodManager，隐藏软键盘
     */
    private void hideKeyboard(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    protected void removeSoftKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }

    public void gotoLoginActivity() {
        Utils.showToast("请您先登录");

        Intent intent = new Intent(BaseActivity.this, LoginActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
    }

    public void gotoLotteryDetailActivity(String code, int index) {//0 其它 1官方2六合3传统
        switch (index) {
            case 1: {
                Intent intent = new Intent(BaseActivity.this, OfficalLotteryDetailActivity.class);
                intent.putExtra("code", code);
                startActivity(intent);
                break;
            }
            case 2: {
                Intent intent = new Intent(BaseActivity.this, LiuhecaiDetailActivity.class);
                intent.putExtra("code", code);
                startActivity(intent);
                break;
            }
            case 3: {
                Intent intent = new Intent(BaseActivity.this, ChuantongcaiActivity.class);
                intent.putExtra("code", code);
                startActivity(intent);
                break;
            }
        }
    }

    protected void gotoSummaryActivity() {
        Intent intent = new Intent(BaseActivity.this, SummaryActivity.class);
        startActivity(intent);
        overridePendingTransition(R.anim.anim_enter_from_bottom, R.anim.activity_stay);
    }

    public interface AfterUpdateAccount {
        void afterUpdateAccount(GetProfileResponse getProfileResponse);
    }

    public void updateAccount(final AfterUpdateAccount afterUpdateAccount) {
        updateAccount(afterUpdateAccount, false);
    }

    public void updateAccount(final AfterUpdateAccount afterUpdateAccount, final boolean showProgres) {
        RetrofitBase.getRetrofit().create(GetProfileRequest.class).getResult(UserInfo.getToken())
                .compose(RxHelper.<GetProfileResponse>handleResult())
                .subscribe(new RxSubscribe<GetProfileResponse>(BaseActivity.this) {
                    @Override
                    protected void _onNext(final GetProfileResponse getProfileResponse) {
                        getProfileActionTime = 0;

                        if (getProfileResponse != null && getProfileResponse.getUser() != null) {
                            UserInfo.setAccount(getProfileResponse.getUser().getAccount());
                            Common.today_profit = getProfileResponse.getToday_lostwin();
                            if (afterUpdateAccount != null) {
                                afterUpdateAccount.afterUpdateAccount(getProfileResponse);
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if (getProfileActionTime >= 5) {
                            return;
                        }
                        getProfileAction = Completable.timer(getProfileActionTime * 2, TimeUnit.SECONDS, AndroidSchedulers.mainThread())
                                .subscribe(new Action() {
                                    @Override
                                    public void run() {
                                        updateAccount(afterUpdateAccount, false);
                                    }
                                });
                        getProfileActionTime++;
                    }

                    @Override
                    protected boolean showDialog() {
                        return showProgres;
                    }
                });
    }

    protected void checkUpdate(final boolean progress, final boolean tip) {
        final NetWaitDialog netWaitDialog = new NetWaitDialog();
        if (progress) {
            netWaitDialog.show(BaseActivity.this);
        }
        //测试/予发布环境走github升级
        //走github升级apk
        String apkHttp = String.format("https://lrgrmxx.com/android/%s/%s_update.json", BuildConfig.COMPANY_CODE, BuildConfig.COMPANY_CODE);
        httpUpdateApk(netWaitDialog, progress, tip, apkHttp);
//        /**
//         * 获取升级动态域名
//         */
//        httpUpdatePreInfo(netWaitDialog, progress, new UpdatePreCallBack() {
//            @Override
//            public void updatePreFail() {
//                //走github升级apk
//                String apkHttp = String.format("https://raw.githubusercontent.com/ruoklive/dynamicdomain/master/company/%s/%s_update.json", BuildConfig.COMPANY_CODE, BuildConfig.COMPANY_CODE);
//                httpUpdateApk(netWaitDialog, progress, tip, apkHttp);
//            }
//
//            @Override
//            public void updatePreSuccess(String apkHttp) {
//                //走服务器升级apk
//                httpUpdateApk(netWaitDialog, progress, tip, apkHttp);
//
//            }
//        });
    }

    /**
     * 升级apk
     *
     * @param apkHttp
     */
    protected void httpUpdateApk(final NetWaitDialog netWaitDialog, final boolean progress, final boolean tip, String apkHttp) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(String.format(apkHttp))
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (progress) {
                            if (netWaitDialog != null) {
                                netWaitDialog.dismissAllowingStateLoss();
                            }
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, final Response response) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (progress) {
                            if (netWaitDialog != null) {
                                netWaitDialog.dismissAllowingStateLoss();
                            }
                        }
                    }
                });

                try {
                    String json = response.body().string();
                    if (json != null) {
                        Gson gson = new Gson();
                        UpdateResponse updateResponse = gson.fromJson(json, UpdateResponse.class);
                        if (Utils.getVersionCode() < updateResponse.getVersion()) {
                            int is_force = 0;
                            if (Utils.getVersionCode() < updateResponse.getCompatible_version()) {
                                is_force = 1;
                            }
                            Version version = new Version(updateResponse.getTitle(), updateResponse.getUrl(), updateResponse.getVersion(), is_force);
                            UpdateDialog dialog = new UpdateDialog();
                            Bundle args = new Bundle();
                            args.putParcelable(UpdateDialog.VERSION, version);
                            args.putString("app_id", getString(R.string.app_id));
                            dialog.setArguments(args);
                            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                            if (dialog != null) {
                                transaction.add(dialog, "update");
                            }
                            transaction.commitAllowingStateLoss();
                            EventBus.getDefault().post(new UpdateApk());
                        } else {
                            if (tip) {
                                runOnUiThread(new Runnable() {
                                                  @Override
                                                  public void run() {
                                                      Utils.showToast("当前已经是最新版本");
                                                  }
                                              }
                                );
                            }
                        }
                    }


                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 获取升级动态域名信息
     */
    protected void httpUpdatePreInfo(final NetWaitDialog netWaitDialog, final boolean progress, final UpdatePreCallBack updatePreCallBack) {
        OkHttpClient client = new OkHttpClient();
        final Request updateInfoRequest = new Request.Builder().url("https://api.ruok.co/cn/cgi/api/config?key=contact_support_link").build();
        Call updateInfoCall = client.newCall(updateInfoRequest);
        updateInfoCall.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (progress) {
                            if (netWaitDialog != null) {
                                netWaitDialog.dismissAllowingStateLoss();
                            }
                        }
                    }
                });
                if (updatePreCallBack != null) {
                    updatePreCallBack.updatePreFail();
                }
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (progress) {
                            if (netWaitDialog != null) {
                                netWaitDialog.dismissAllowingStateLoss();
                            }
                        }
                    }
                });
                String json = response.body().string();
                if (json != null) {
                    Gson gson = new Gson();
                    UpdatePreResponse updatePreResponse = gson.fromJson(json, UpdatePreResponse.class);
                    if (updatePreResponse != null) {
                        String androidUpdateHttpPre = updatePreResponse.getAndroid_dl();
                        if (!Utils.isEmpty(androidUpdateHttpPre)) {
                            String updateHttp = String.format("%s/%s/%s_update.json", androidUpdateHttpPre, BuildConfig.COMPANY_CODE, BuildConfig.COMPANY_CODE);
                            if (updatePreCallBack != null) {
                                updatePreCallBack.updatePreSuccess(updateHttp);
                            }
                            return;
                        }
                    }
                }
                if (updatePreCallBack != null) {
                    updatePreCallBack.updatePreFail();
                }
            }


        });
    }

    protected void logOut() {
        MobiComDatabaseHelper.getInstance(getApplicationContext()).delDatabase();

        UserInfo.setToken("");
        UserInfo.setAvatar("");
        UserInfo.setRoomId("");
        UserInfo.setAdmin("");
        UserInfo.setRongCloudToken("");
//        BubbleUtils.clearAll();
//        ChatRecordUtils.clearAll();
//        SearchRecordUtils.clearAll();
        ApplozicClient.getInstance(getApplicationContext()).setRoomId(0);
        EventBus.getDefault().post(new LogOut());
    }

    //    protected void getService(){
//        RetrofitBase.getRetrofit().create(GetHasSMSRequest.class).getResult("contact_support_link")
//                .compose(RxHelper.<GetHasSMSResponse>handleResult())
//                .subscribe(new RxSubscribe<GetHasSMSResponse>(this) {
//                    @Override
//                    protected void _onNext(GetHasSMSResponse getHasSMSResponse) {
//                        if(getHasSMSResponse != null && getHasSMSResponse.getValue() != null && !getHasSMSResponse.getValue().toString().equals("null")){
//                            Utils.openBrowser(getHasSMSResponse.getValue().toString(), BaseActivity.this);
//                        } else {
//                            Utils.showToast(getApplicationContext(), Common.NO_SERVICE);
//                        }
//                    }
//
//                    @Override
//                    protected boolean showDialog() {
//                        return false;
//                    }
//                });
//    }



    /**
     * 请求动态升级域名回调
     */
    interface UpdatePreCallBack {
        void updatePreFail();

        void updatePreSuccess(String apkHttp);
    }
}
